import dayjs from "dayjs";

/*
 * @Author: wangyongcun
 * @Date: 2023-09-06 10:50:08
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-06-12 21:49:52
 * @Description: 成果库管理
 */
class Policy {
  constructor() {
    this.policyTypeList = [];
    this.queryPolicyType();
  }
  /**
   * @description: 添加技术成果
   * @param {*} ctx
   * @return {*}
   */
  async addPolicy(ctx) {
    try {
      // 获取参数
      let isEmpty = reqUtil.isEmpty(
        ["title", "pubAgency", "pubDate", "content"],
        ctx
      );
      if (isEmpty) return;
      // 查询数据是否已存在
      // 添加到数据库
      let rowBody = ctx.request.body;
      let rowBodyKeys = Object.keys(rowBody);
      let sqlParams = `id='${uuidv4()}',`;
      rowBodyKeys.forEach((x, i) => {
        sqlParams += `${x}='${rowBody[x]}'${
          i == rowBodyKeys.length - 1 ? "" : ","
        }`;
      });
      let sql = `INSERT INTO policy SET ${sqlParams}`;
      let { status } = await db(sql);
      if (status != 200) throw "添加政策失败";
      // 返回结果
      ctx.body = resUtil.success("添加成功");
    } catch (err) {
      log.error(`Policy-addPolicy-添加政策失败：${err}`);
      ctx.body = resUtil.error(err);
    }
  }
  /**
   * @description: 更新技术成果
   * @param {*} ctx
   * @return {*}
   */
  async updatePolicy(ctx) {
    try {
      // 获取参数
      let isEmpty = reqUtil.isEmpty(["id"], ctx);
      if (isEmpty) return;
      // 查询数据是否已存在
      // 添加到数据库
      let rowBody = ctx.request.body;
      let rowBodyKeys = Object.keys(rowBody);
      let sqlParams = "";
      rowBodyKeys.forEach((x, i) => {
        sqlParams += `${x}='${rowBody[x]}'${
          i == rowBodyKeys.length - 1 ? "" : ","
        }`;
      });
      let sql = `UPDATE policy SET ${sqlParams} WHERE id='${rowBody.id}'`;
      let { status, results } = await db(sql);
      if (status != 200 || results.affectedRows == 0) throw "更新账号失败";
      // 返回结果
      ctx.body = resUtil.success("更新成功");
    } catch (err) {
      log.error(`Policy-updatePolicy-更新失败：${err}`);
      ctx.body = resUtil.error(err);
    }
  }
  /**
   * @description: 删除用户
   * @param {*} ctx
   * @return {*}
   */
  async deletePolicy(ctx) {
    try {
      // 获取参数
      let isEmpty = reqUtil.isEmpty(["id"], ctx);
      if (isEmpty) return;
      // 添加到数据库
      let rowBody = ctx.request.body;
      let sql = `DELETE FROM policy WHERE id='${rowBody.id}'`;
      let { status, results } = await db(sql);
      if (status != 200 || results.affectedRows == 0) throw "未找到该政策";
      // 返回结果
      ctx.body = resUtil.success("删除成功");
    } catch (err) {
      log.error(`Policy-deletePolicy-删除失败：${err}`);
      ctx.body = resUtil.error(err);
    }
  }
  /**
   * @description: 查询技术成果
   * @param {*} ctx
   * @return {*}
   */
  async queryPolicy(ctx) {
    try {
      // 获取参数
      let isEmpty = reqUtil.isEmpty(["id"], ctx);
      if (isEmpty) return;
      // 添加到数据库
      let rowBody = ctx.request.body;
      let sql = `SELECT * FROM policy WHERE id='${rowBody.id}'`;
      let { status, results } = await db(sql);
      if (status != 200 || results.length == 0) throw "未找到该政策";
      // 返回结果
      let Content = results[0];
      Content.pubDate = dayjs(Content.pubDate).format("YYYY-MM-DD");
      ctx.body = resUtil.success({ Content: Content });
    } catch (err) {
      log.error(`Policy-queryPolicy-查询失败：${err}`);
      ctx.body = resUtil.error(err);
    }
  }
  /**
   * @description: 查询列表
   * @param {*} ctx
   * @return {*}
   */
  async queryPolicyList(ctx) {
    try {
      // 获取参数
      let isEmpty = reqUtil.isEmpty(["pageNum", "pageSize"], ctx);
      if (isEmpty) return;
      let { pageNum, pageSize, keyword, type } = ctx.request.body;
      let whereSql = "";
      if (keyword) {
        whereSql += keyword ? `WHERE title LIKE '%${keyword}%'` : "";
      }
      if (type) {
        whereSql += `${whereSql ? " AND " : "WHERE "} type='${type}'`;
      }
      // 查询总条数
      let Count = 0;
      let countSql = `SELECT COUNT(1) FROM policy ${whereSql}`;
      let { status: countStatus, results: countRes } = await db(countSql);
      if (countStatus != 200) throw "查询总条数失败";
      Count = countRes[0]["COUNT(1)"];
      // 查询列表数据
      let listSql = `SELECT * FROM policy ${whereSql} ORDER BY pubDate DESC LIMIT ${pageSize} OFFSET ${
        pageSize * (pageNum - 1)
      }`;
      let { status: listStatus, results: listRes } = await db(listSql);
      if (listStatus != 200) throw "查询政策列表失败";
      // 返回结果
      listRes.forEach((item) => {
        let typeObj = this.policyTypeList.find((x) => x.value == item.type);
        item.typeName = typeObj.label;
        item.typeBgColor = typeObj.bgColor;
        item.typeTextColor = typeObj.textColor;
        item.pubDate = dayjs(item.pubDate).format("YYYY-MM-DD");
      });
      ctx.body = resUtil.success({ Content: listRes, Count });
    } catch (err) {
      log.error(`Policy-queryPolicyList-查询失败：${err}`);
      ctx.body = resUtil.error(err);
    }
  }
  /**
   * @description: 查询政策类型
   * @param {*} ctx
   * @return {*}
   */
  async queryPolicyType(ctx) {
    try {
      // 查询列表数据
      let listSql = `SELECT * FROM policy_type`;
      let { status: listStatus, results: listRes } = await db(listSql);
      if (listStatus != 200) throw "查询政策类型失败";
      // 返回结果
      this.policyTypeList = listRes;
      if (ctx) {
        ctx.body = resUtil.success({ Content: listRes });
      }
    } catch (err) {
      log.error(`Policy-queryPolicyType-查询失败：${err}`);
      if (ctx) {
        ctx.body = resUtil.error(err);
      }
    }
  }
}

export default new Policy();
